package leetcode.editor.day;

import java.util.Arrays;

// 1624. 两个相同字符之间的最长子字符串
// https://leetcode.cn/problems/largest-substring-between-two-equal-characters/
class LargestSubstringBetweenTwoEqualCharacters {
    public static void main(String[] args) {
        Solution solution = new LargestSubstringBetweenTwoEqualCharacters().new Solution();
        // solution.maxLengthBetweenEqualCharacters("aa");
        solution.maxLengthBetweenEqualCharacters("abaccca");
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        // 暴力
        /*public int maxLengthBetweenEqualCharacters(String s) {
            int res = -1;
            for (int i = 0; i < s.length(); i++) {
                for (int j = i + 1; j < s.length(); j++) {
                    if (s.charAt(i) == s.charAt(j)) {
                        res = Math.max(res, j - i - 1);
                    }
                }
            }

            return res;
        }*/

        // hash表
        public int maxLengthBetweenEqualCharacters(String s) {
            int[] arr = new int[26];
            Arrays.fill(arr, -1);
            int res = -1;
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (arr[c - 'a'] == -1) arr[c - 'a'] = i;   //  赋值第一次索引
                else res = Math.max(res, i - arr[c - 'a'] - 1); // 更新长度即可
            }

            return res;
        }

    }
//leetcode submit region end(Prohibit modification and deletion)

}
